﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;

namespace Reports.YULIA
{
    public partial class NewGoodsReport : Form, IntegrationInterface.IDIProjectForm,IntegrationInterface.IDIReport
    {
        public NewGoodsReport(string conString, string login, object commonProp)
        {
            InitializeComponent();
            this.Login = login;
            this.ConnectionString = conString;
            this.CommonProperty = commonProp;
            InitAdpters();
        }
        public NewGoodsReport()
        {
            InitializeComponent();
        }
        private void InitAdpters()
        {
            this.goodsTableAdapter.Connection.ConnectionString = this.ConnectionString;
            this.manufacturersTableAdapter.Connection.ConnectionString = this.ConnectionString;
            this.sellersTableAdapter.Connection.ConnectionString = this.ConnectionString;
            this.departmentsTableAdapter.Connection.ConnectionString = this.ConnectionString;
        }
        private void LoadData()
        {
            LoadInfoForm lif = new LoadInfoForm();
            lif.Show();
            // TODO: This line of code loads data into the 'dataSet.Goods' table. You can move, or remove it, as needed.
            this.goodsTableAdapter.Fill(this.dataSet.Goods);
            // TODO: This line of code loads data into the 'dataSet.Sellers' table. You can move, or remove it, as needed.
            this.sellersTableAdapter.Fill(this.dataSet.Sellers);
            // TODO: This line of code loads data into the 'dataSet.Manufacturers' table. You can move, or remove it, as needed.
            this.manufacturersTableAdapter.Fill(this.dataSet.Manufacturers);
            // TODO: This line of code loads data into the 'dataSet.Departments' table. You can move, or remove it, as needed.
            this.departmentsTableAdapter.Fill(this.dataSet.Departments);
            lif.Close();
        }
        private void NewGoodsReport_Load(object sender, EventArgs e)
        {
           // LoadData();
        }
        #region выделенные значения
        private List<Int32> SelDept
        {
            get
            {
                List<Int32> result = new List<Int32>();
                foreach (YULIA.DataSet.DepartmentsRow dr in this.dataSet.Departments)
                {
                    if (dr.Sel)
                    {
                        result.Add(dr.Id);
                    }
                }
                return result;
            }
        }
        private List<Int32> SelSellers
        {
            get
            {
                List<Int32> result = new List<Int32>();
                foreach (YULIA.DataSet.SellersRow sr in this.dataSet.Sellers)
                {
                    if (sr.Sel)
                    {
                        result.Add(sr.Id);
                    }
                }
                return result;
            }
        }
        private List<Int32> SelGoods
        {
            get
            {
                List<Int32> result = new List<Int32>();
                foreach (YULIA.DataSet.GoodsRow gr in this.dataSet.Goods)
                {
                    if (gr.Sel)
                    {
                        result.Add(gr.Id);
                    }
                }
                return result;
            }
        }
        private List<Int32> SelManufacturers
        {
            get
            {
                List<Int32> result = new List<Int32>();
                foreach (YULIA.DataSet.ManufacturersRow mr in this.dataSet.Manufacturers)
                {
                    if (mr.Sel)
                    {
                        result.Add(mr.Id);
                    }
                }
                return result;
            }
        }
        #endregion
        #region фильтры
        private string GetList(List<Int32> list)
        {
            if (list.Count == 0)
                return string.Empty;
           // XmlDocument doc = new XmlDocument();
           // XmlElement root = doc.CreateElement("root");
          //  doc.AppendChild(root);
            Int32 tmp = list.Count;
            StringBuilder sb = new StringBuilder(" (");
            for (Int32 i = 0; i<tmp; i++)
            {
               // XmlElement item = doc.CreateElement("item");
              //  root.AppendChild(item);
              //  item.InnerText = Convert.ToString(i);
                sb.Append(list[i]);
                if (i != (tmp - 1))
                    sb.Append(",");

            }
            sb.Append(") ");
            sb.Append(Environment.NewLine);
            return sb.ToString();
           // return doc.OuterXml;
        }
        private string GetXML(List<Int32> list)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.CreateElement("root");
            doc.AppendChild(root);
            foreach (Int32 i in list)
            {
                XmlElement item = doc.CreateElement("item");
                root.AppendChild(item);
                item.InnerText = Convert.ToString(i);
            }
            return doc.OuterXml;
        }
        private string DepartmentsFilrt
        {
            get
            {
                List<Int32> tmp = this.SelDept;
                if (tmp.Count == 0)
                    return string.Empty;
                return this.GetList(tmp);
            }
        }
        private string SellersFiltr
        {
            get
            {
                List<Int32> tmp = this.SelSellers;
                if (tmp.Count == 0)
                    return string.Empty;
                return this.GetList(tmp);
            }
        }
        private string ManufacturersFiltr
        {
            get
            {
                List<Int32> tmp = this.SelManufacturers;
                if (tmp.Count == 0)
                    return string.Empty;
                return this.GetList(tmp);
            }
        }
        private string GoodsFiltr
        {
            get
            {
                List<Int32> tmp = this.SelGoods;
                if (tmp.Count == 0)
                    return string.Empty;
                return this.GetList(tmp);
            }
        }
        private DateTime BeginDate
        {
            get
            {
                return this.dtpDateBegin.Value.Date;
            }
        }
        private DateTime EndDate
        {
            get
            {
                return this.dtpDateEnd.Value.Date.AddDays(1);
            }
        }
        #endregion
        #region IDIProjectForm Members
        public object _comProp;
        public object CommonProperty
        {
            get
            {
                return _comProp;
            }
            set
            {
                _comProp = value;
            }
        }
        string _conStr;
        public string ConnectionString
        {
            get
            {
                return _conStr;
            }
            set
            {                
                _conStr = value;
                InitAdpters();
                LoadData();
            }
        }
        string _log;
        public string Login
        {
            get
            {
                return _log;
            }
            set
            {
                _log = value;
            }
        }

        public Form MailForm
        {
            get 
            {
                return this;
            }
        }

        #endregion
        #region подготовка запроса
        string BaseQueryString = @"
SELECT     CO.Departments.Name as DeptName, 
case when CA.GoodsDocLines.Qntty > 0 then CA.GoodsDocLines.Qntty else -CA.GoodsDocLines.Qntty end  as [Count], 
case when CA.GoodsDocLines.RetailSum > 0 then CA.GoodsDocLines.RetailSum else -CA.GoodsDocLines.RetailSum end as [Sum], 
vwGoodsDetailed.FullName as GoodName, CD.Parties.BarCode, vwInputLines.NDSTax as NDS, 
vwInputLines.BatchNumber as Seria, CA.Documents.DocDate, 
CO.DocTypes.ShortName as [Type], CA.Contragents.ShortName AS SellerName,
CO.Manufacturers.ShortName as Manufacturers,vwGoodsDetailed.Id as GoodsId
FROM         CO.DocTypes INNER JOIN
CA.Documents ON CO.DocTypes.Id = CA.Documents.DocTypeId INNER JOIN
CA.GoodsDocLines INNER JOIN
CO.Departments ON CA.GoodsDocLines.DepartmentId = CO.Departments.Id INNER JOIN
CD.Parties ON CA.GoodsDocLines.PartyId = CD.Parties.Id INNER JOIN
vwGoodsDetailed ON CD.Parties.GoodsId = vwGoodsDetailed.Id 
ON CA.Documents.Id = CA.GoodsDocLines.DocId INNER JOIN
CA.Contragents ON CA.Documents.ContragentId = CA.Contragents.Id LEFT OUTER JOIN
vwInputLines ON CD.Parties.InputLineId = vwInputLines.Id
INNER JOIN CA.Goods on CA.Goods.Id = CD.Parties.GoodsId INNER JOIN
CO.Manufacturers ON CO.Manufacturers.Id = CA.Goods.ManufacturerId
where CA.Documents.DocDate >= @db and CA.Documents.DocDate < @de ";
        private SqlCommand CreateCommand(SqlConnection connection)
        {
            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.Parameters.AddWithValue("@db", this.BeginDate);
            command.Parameters.AddWithValue("@de", this.EndDate);
            StringBuilder sb = new StringBuilder(BaseQueryString);
            string tmp = this.DepartmentsFilrt;
            if (!string.IsNullOrEmpty(tmp))
            {
                string sd = " AND CA.Documents.DepartmentId IN  " + this.DepartmentsFilrt; //(select t.c.value('.','int') from @SD.nodes('root/item') t(c) ) ";
                sb.Append(sd);
               // SqlParameter sdxml = new SqlParameter("@SD", SqlDbType.Xml);
             //   sdxml.Value = tmp;
              //  command.Parameters.Add(sdxml);
            }
            tmp = this.SellersFiltr;
            if (!string.IsNullOrEmpty(tmp))
            {
                string ss = " AND CA.Contragents.Id IN  " + this.SellersFiltr;//(select t.c.value('.','int') from @SS.nodes('root/item') t(c) ) ";
                sb.Append(ss);
                //SqlParameter ssxml = new SqlParameter("@SS", SqlDbType.Xml);
               // ssxml.Value = tmp;
               // command.Parameters.Add(ssxml);
            }
            tmp = this.ManufacturersFiltr;
            if (!string.IsNullOrEmpty(tmp))
            {
                string sm = " AND CO.Manufacturers.Id IN  " + this.ManufacturersFiltr;//(select t.c.value('.','int') from @SM.nodes('root/item') t(c) ) ";
                sb.Append(sm);
               // SqlParameter smxml = new SqlParameter("@SM", SqlDbType.Xml);
               // smxml.Value = tmp;
               // command.Parameters.Add(smxml);
            }
            tmp = this.GoodsFiltr;
            if (!string.IsNullOrEmpty(tmp))
            {
                string sg = " AND CA.Goods.Id IN  " + this.GoodsFiltr;//(select t.c.value('.','int') from @SG.nodes('root/item') t(c) ) ";
                sb.Append(sg);
               // SqlParameter sgxml = new SqlParameter("@SG", SqlDbType.Xml);
              //  sgxml.Value = tmp;
               // command.Parameters.Add(sgxml);
            }
            command.CommandText = sb.ToString();
            return command;
        }
        private SqlCommand CreateCommand2(SqlConnection connection)
        {
            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.Parameters.AddWithValue("@db", this.BeginDate);
            command.Parameters.AddWithValue("@de", this.EndDate);
            StringBuilder sb = new StringBuilder(BaseQueryString);
            string tmp = this.DepartmentsFilrt;
            if (!string.IsNullOrEmpty(tmp))
            {
                string sd = " AND CA.Documents.DepartmentId IN  (select t.c.value('.','int') from @SD.nodes('root/item') t(c) ) ";
                sb.Append(sd);
                SqlParameter sdxml = new SqlParameter("@SD", SqlDbType.Xml);
                sdxml.Value = tmp;
                command.Parameters.Add(sdxml);
            }
            tmp = this.SellersFiltr;
            if (!string.IsNullOrEmpty(tmp))
            {
                string ss = " AND CA.Contragents.Id IN  (select t.c.value('.','int') from @SS.nodes('root/item') t(c) ) ";
                sb.Append(ss);
                SqlParameter ssxml = new SqlParameter("@SS", SqlDbType.Xml);
                ssxml.Value = tmp;
                command.Parameters.Add(ssxml);
            }
            tmp = this.ManufacturersFiltr;
            if (!string.IsNullOrEmpty(tmp))
            {
                string sm = " AND CO.Manufacturers.Id IN  (select t.c.value('.','int') from @SM.nodes('root/item') t(c) ) ";
                sb.Append(sm);
                SqlParameter smxml = new SqlParameter("@SM", SqlDbType.Xml);
                smxml.Value = tmp;
                command.Parameters.Add(smxml);
            }
            tmp = this.GoodsFiltr;
            if (!string.IsNullOrEmpty(tmp))
            {
                string sg = " AND CA.Goods.Id IN  (select t.c.value('.','int') from @SG.nodes('root/item') t(c) ) ";
                sb.Append(sg);
                SqlParameter sgxml = new SqlParameter("@SG", SqlDbType.Xml);
                sgxml.Value = tmp;
                command.Parameters.Add(sgxml);
            }
            command.CommandText = sb.ToString();
            return command;
        }
        #endregion

        private void cbAll_CheckedChanged(object sender, EventArgs e)
        {
            ToolStripButton tsb = sender as ToolStripButton;
            if (tsb == null)
                return;
            if (tsb.Checked)
            {
                tsb.Text = "Снять выделение";
            }
            else
            {
                tsb.Text = "Выделить все";
            }
            bool tmp = tsb.Checked;
            string str = (string)tsb.Tag;
            if (str == null)
                return;
            switch (str)
            {
                case "1":
                    this.Sel_Dept(tmp);
                    break;
                case "2":
                    this.Sel_Sellers(tmp);
                    break;
                case "3":
                    this.Sel_Manufacturers(tmp);
                    break;
                case "4":
                    this.Sel_Goods(tmp);
                    break;
                default:
                    throw new Exception("Ошибка");
            }
        }
       
        private void Sel_Dept(bool sel)
        {
            foreach (YULIA.DataSet.DepartmentsRow dr in this.dataSet.Departments)
            {
                dr.Sel = sel;
            }
        }
        private void Sel_Sellers(bool sel)
        {
            foreach (YULIA.DataSet.SellersRow sr in this.dataSet.Sellers)
            {
                sr.Sel = sel;
            }
        }
        private void Sel_Manufacturers(bool sel)
        {
            foreach (YULIA.DataSet.ManufacturersRow mr in this.dataSet.Manufacturers)
            {
                mr.Sel = sel;
            }
        }
        private void Sel_Goods(bool sel)
        {
            foreach (YULIA.DataSet.GoodsRow gr in this.dataSet.Goods)
            {
                gr.Sel = sel;
            }
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            string rPath = (string)this.CommonProperty;
            InitReport(rPath);
        }


        #region IDIReport Members

        public void InitReport(string reportPath)
        {
            FromDept1.FileName = reportPath + "FromDept.rpt";
            FromDept1.Load();
            FromGoods1.FileName = reportPath + "FromGoods.rpt";
            FromGoods1.Load();
            using (SqlConnection connection = new SqlConnection(this.ConnectionString))
            {
                try
                {
                    SqlCommand command = this.CreateCommand(connection);
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    adapter.Fill(this.dataSet.Data);
                }
                catch (SqlException se)
                {
                    MessageBox.Show("Ошибка\n" + se.Message);
                }
                catch (Exception ee)
                {
                    MessageBox.Show("Ошибка\n" + ee.Message);
                }
            }
            
            FromDept1.SetDataSource(this.dataSet.Data as DataTable);
            FromGoods1.SetDataSource(this.dataSet.Data as DataTable);
            FromDept1.SetParameterValue("host", Util.Common.HostName);
            FromGoods1.SetParameterValue("host", Util.Common.HostName);
            crystalReportViewer1.DisplayToolbar = true;
            crystalReportViewer1.DisplayStatusBar = true;
            crystalReportViewer1.DisplayGroupTree = true;
            crystalReportViewer2.DisplayGroupTree = true;
            crystalReportViewer2.DisplayStatusBar = true;
            crystalReportViewer2.DisplayToolbar = true;
        }
        private string gFiltr
        {
            get
            {
                string tmp = txbGoodsFiltr.Text;
                if (string.IsNullOrEmpty(tmp))
                {
                    return string.Empty;
                }
                return tmp;
            }
        }
        #endregion

        private void txbGoodsFiltr_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (this.gFiltr == string.Empty)
                {
                    goodsBindingSource.Filter = string.Empty;
                    return;
                }
                goodsBindingSource.Filter = "FullName LIKE '*" + this.gFiltr + "*'";
            }
        }
    }
}